package com.pug.service.message;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pug.dto.UserDto;
import com.pug.mapper.message.UserMqRepository;
import com.pug.mapper.mq.IMqServiceMapper;
import com.pug.pojo.MqService;
import com.pug.result.ResultEnum;
import com.pug.result.ex.KsdValidationException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Author: lqm
 * create: 2022/5/7 19:26
 * Lover: lqx
 *
 * @see
 */
@Component
@Slf4j
public class UserFromRoot {
    public static final String User_direct_queue="User_direct_queue";
    public static final String User_direct_exchange="User_direct_exchange";
    public static final String User_direct_key="User_direct_key";
    @Resource
    IMqServiceMapper iMqServiceMapper;
    @Qualifier("redisTemplate")
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Resource
    UserMqRepository userMqRepository;

    /**
     * 这个地方保证了登录消息的不重复消费
     * @param userDto
     * @param message
     * @param channel
     */
    //处理来自用户模块用户信息登录信息的保存
    @RabbitListener(queues = {User_direct_queue},
            containerFactory = "simpleTopicOrderDeadContainerAuto")
    public void consumerOrder(@Payload UserDto userDto, Message message, Channel channel) {
        try {
            //拿到mq消息id先
            String messageId = message.getMessageProperties().getMessageId();
            //查询mq-service表中是否已经有这个消息id了，如果有就代表次消息已经被消费了。
            QueryWrapper<MqService> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("mq_service_id",messageId);
            MqService mqService = iMqServiceMapper.selectOne(queryWrapper);
            //消息重复消费，直接抛异常
            if(mqService!=null) throw new KsdValidationException(ResultEnum.MESSAGE_REPEAT);
            //拿到mq消息id，然后准备保存到mq-service表中
            MqService mqService1 = new MqService();
            mqService1.setMqServiceId(messageId);
            iMqServiceMapper.insert(mqService1);

            userDto.setCreateTime(new Date()+"");
            userMqRepository.save(userDto);
        } catch (Exception ex) {
            log.error("登录出错：{}", userDto);
        }
    }
    //处理来自用户模块用户信息注册信息的保存
}
